package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.base.ResponseResult;
import com.zzyl.config.DingTalkClient;
import com.zzyl.dto.AlertRuleDTO;
import com.zzyl.entity.AlertRule;
import com.zzyl.entity.DeviceData;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.mapper.DeviceDataMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.vo.AlertRuleVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.DeleteMapping;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AlertRuleServiceImpl implements AlertRuleService {

    @Resource
    private AlertRuleMapper alertRuleMapper;

    @Resource
    DeviceDataMapper deviceDataMapper;

    @Resource
    DingTalkClient dingTalkClient;

    @Override
    public ResponseResult createAlertRule(AlertRuleDTO alertRuleDto) {
        AlertRule alertRule = BeanUtil.toBean(alertRuleDto, AlertRule.class);
        alertRule.setProductId(alertRuleDto.getProductKey());
        alertRule.setRelatedDevice(alertRuleDto.getDeviceId());
        alertRule.setCreateTime(LocalDateTime.now());
        alertRule.setUpdateTime(LocalDateTime.now());
        int insert = alertRuleMapper.insert(alertRule);
        if (insert==0){
            return ResponseResult.error("添加失败");
        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult<PageResponse<AlertRuleVo>> getAlertRulePage(Integer pageNum,
                                                                      Integer pageSize,
                                                                      String alertRuleName,
                                                                      String productKey,
                                                                      String functionName) {
        Page<Object> page = PageHelper.startPage(pageNum, pageSize);
        List<AlertRule> alertRules = alertRuleMapper.queryAllByLimit(alertRuleName, productKey, functionName);
        List<AlertRuleVo> collect = alertRules.stream().map(alertRule -> {
            AlertRuleVo alertRuleVo = new AlertRuleVo();
            BeanUtils.copyProperties(alertRule, alertRuleVo);
            alertRuleVo.setRules(alertRule.getOperator() + alertRule.getValue());
            return alertRuleVo;
        }).collect(Collectors.toList());
        PageResponse<AlertRuleVo> pageResponse = PageResponse.of(collect);
        pageResponse.setTotal(page.getTotal());
        return ResponseResult.success(pageResponse);
    }

    @Override
    public ResponseResult<AlertRuleVo> getAlertRuleById(Long id) {
        AlertRule alertRule = alertRuleMapper.queryById(id);
        AlertRuleVo alertRuleVo = new AlertRuleVo();
        BeanUtils.copyProperties(alertRule, alertRuleVo);
        alertRuleVo.setProductKey(alertRule.getProductId());
        return ResponseResult.success(alertRuleVo);
    }

    @Override
    public ResponseResult updateAlertRule(AlertRuleDTO dto) {
        AlertRule alertRule = new AlertRule();
        BeanUtils.copyProperties(dto, alertRule);
        alertRule.setProductId(dto.getProductKey());
        alertRule.setRelatedDevice(dto.getDeviceId());
        alertRule.setUpdateTime(LocalDateTime.now());
        alertRule.setValue((float) dto.getValue());
        int insert = alertRuleMapper.update(alertRule);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult updateAlertRuleStatus(Integer id, Integer status) {
        AlertRule alertRule = alertRuleMapper.queryById(Long.valueOf(id));
        alertRule.setStatus(status);
        alertRuleMapper.update(alertRule);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult deleteAlertRule(Long id) {
        alertRuleMapper.deleteById(id);
        return ResponseResult.success();
    }

    @Override
    public void alertFilter(List<DeviceData> deviceDataList) {
        log.info("开始过滤数据{}", deviceDataList);
        if (CollectionUtil.isEmpty(deviceDataList)){
            return;
        }
        List<AlertRule> alertRules = alertRuleMapper.
                queryAlertRuleByProductId(deviceDataList.get(0).getProductId());
        if (CollectionUtil.isEmpty(alertRules)){
            return;
        }
        //判断告警规则的生效时间以及规则状态
        alertRules.forEach(alertRule -> {
            String[] split = alertRule.getAlertEffectivePeriod().split("~");
            LocalTime start = LocalTime.parse(split[0]);
            LocalTime end = LocalTime.parse(split[1]);
            Optional<DeviceData> first = deviceDataList.stream().filter(device -> device.getFunctionName()
                    .equals(alertRule.getFunctionId())).findFirst();
            DeviceData deviceData = first.get();
            LocalTime localTime = deviceData.getAlarmTime().toLocalTime();
            if (localTime.isAfter(start) && localTime.isBefore(end)){
                Float value = alertRule.getValue();
                String operator = alertRule.getOperator();
                Float alertValue = Float.valueOf(deviceData.getDataValue());
               if (operator.equals(">=")){
                    if (alertValue.compareTo(value)>=0){
                        deviceData.setStatus("1");
                        int insert = deviceDataMapper.insert(deviceData);
                        log.info("插入告警数据{}tiao", insert);
                        dingTalkClient.sendTextMsg("老人董文祥硬了，快去给他降降火", true, Collections.singletonList(""));
                        dingTalkClient.sendLinkMsg("http://localhost:3001","全国可飞","https://tse4-mm.cn.bing.net/th/id/OIP-C.C5kcebrQdDbdXzMSLIJDeAHaKX?w=128&h=180&c=7&r=0&o=5&dpr=1.3&pid=1.7");
                    }else {
                        deviceData.setStatus("0");
                        //插入正常上报数据
                        deviceDataMapper.insert(deviceData);
                    }
               }else {
                   if (alertValue.compareTo(value)<0){
                       deviceData.setStatus("1");
                       deviceDataMapper.insert(deviceData);
                   }else {
                       deviceData.setStatus("0");
                       //插入正常上报数据
                       deviceDataMapper.insert(deviceData);
                   }
               }
            }

        });
    }
}
